package com.ifast.face.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ifast.common.annotation.Log;
import com.ifast.common.annotation.OperateRecord;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.service.DictService;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.alioss.OSSBjOtherClientUtil;
import com.ifast.common.utils.alioss.UploadResult;
import com.ifast.face.domain.Camera;
import com.ifast.face.domain.UserFaceInfo;
import com.ifast.face.service.CameraService;
import com.ifast.face.service.UserFaceInfoService;
import com.ifast.sys.domain.UserDO;

import cn.hutool.core.date.DateUtil;

/**
 * 摄像头视频添加
 */
@Controller
@RequestMapping("/video")
public class VideoController extends AdminBaseController{ 
	 
	private String preHtml = "video/manage/";
    
    @Autowired
    private CameraService cameraService; 
	@Autowired
    private UserFaceInfoService userFaceInfoService;
	@Autowired
    private DictService sysDictService;
	
    @GetMapping()
    @RequiresPermissions("video:manage:info")
    String CameraText(Model model,Camera camera){
    	 
    	Page<Camera> page = getPage(Camera.class); 
    	page.setSize(5);
        page = (Page<Camera>) cameraService.page(page, new QueryWrapper<Camera>().eq(StringUtils.isNotBlank(camera.getGroupType()),"group_type",camera.getGroupType()).like(StringUtils.isNotBlank(camera.getName()), "name", camera.getName()).orderByDesc("sort").orderByDesc("CREATE_TIME"));
        if(page!=null && page.getRecords() != null){
        	page.getRecords().stream().forEach(cam -> {cam.setGroupName(sysDictService.getName("group_type", cam.getGroupType()));});
        } 
        model.addAttribute("page", page);
        model.addAttribute("camera", camera);
        return preHtml+ "list";
    }
    
    @ResponseBody
    @GetMapping("/list") 
    public Result<Page<Camera>> list(Integer pageNumber, Integer pageSize, Camera fileDTO) {
        // 查询列表数据
    	Page<Camera> page = getPage(Camera.class); 
        page = (Page<Camera>) cameraService.page(page, new QueryWrapper<Camera>(fileDTO).orderByDesc("CREATE_TIME"));
        if(page!=null && page.getRecords() != null){
        	page.getRecords().stream().forEach(cam -> {cam.setGroupName(sysDictService.getName("group_type", cam.getGroupType()));});
        } 
        return Result.ok(page);
    } 
    
    @GetMapping("/add")
    @RequiresPermissions("video:manage:add")
    public String addText(Model model, String id){ 
        return  preHtml+"add";
    }
   
    @GetMapping("/edit/{id}")
    @RequiresPermissions("video:manage:edit")
    public String editText(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",cameraService.getById(id));
        return  preHtml+"edit";
    } 
    
   
    @GetMapping("/viewPush/{id}")
    @RequiresPermissions("video:manage:view")
    public String viewPush(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",cameraService.getById(id));
        return  preHtml+"view_push";
    } 
    
    @GetMapping("/viewSrc/{id}")
    @RequiresPermissions("video:manage:view")
    public String viewSrc(Model model,@PathVariable("id") String id){
    	model.addAttribute("info",cameraService.getById(id));
        return  preHtml+"view_src";
    } 
     
    @GetMapping("/viewFace")
    @RequiresPermissions("video:manage:view")
    public String viewFace(Model model,String groupType){ 
    	List<Camera> cams = Lists.newArrayList();
    	if(StringUtils.isNotBlank(groupType)){ 
    		cams = cameraService.list(new QueryWrapper<Camera>().eq("status", "1").eq("group_type", groupType));
        	if(CollectionUtils.isNotEmpty(cams)){
        		cams.stream().forEach(cam -> {cam.setGroupName(sysDictService.getName("group_type", cam.getGroupType()));});
            } 
    	} 
    	model.addAttribute("vars",cams);
    	model.addAttribute("groupType",groupType);
        return  preHtml+"view_face";
    } 
    
    @GetMapping("/viewImg")
    @RequiresPermissions("video:manage:view")
    public String viewImg(Model model,String url){
    	model.addAttribute("url",url);
        return  preHtml+"view_img";
    } 
    
   	@RequestMapping(value="/uploadvideo")
   	@ResponseBody 
   	public UploadResult uploadVideo(HttpServletRequest request) {
   		OSSBjOtherClientUtil ossClientUtil = OSSBjOtherClientUtil.getInstance();
   		UploadResult ur = ossClientUtil.uploadImg2OssMoreFile(request, "Camera/video/yuan");
   		if(ur!=null && ur.getFileURLs()!=null && ur.getFileURLs().size()>0){
   			ur.getFileURLs().add(ur.getFileURLs().get(0).split("\\?")[0]+"?x-oss-process=video/snapshot,t_10000,m_fast");
   		}  
   		return ur;
   	}
   	
  
    @PostMapping("/remove")
    @ResponseBody
    @Log("删除")
    @RequiresPermissions("video:manage:delete")
    public Result<?> remove(Model model,String id){  
        return  cameraService.removeById(id) ? Result.ok():Result.fail();
    } 
    
    @PostMapping("/push")
    @ResponseBody
    @Log("视频推送")
    @RequiresPermissions("video:manage:edit")
    public Result<?> push(Model model,String id){  
        return  cameraService.push(id,this.getUserId()+"");
    } 

    @PostMapping("/endPush")
    @ResponseBody
    @Log("取消推送")
    @RequiresPermissions("video:manage:edit")
    public Result<?> endPush(Model model,String id){  
        return  cameraService.endPush(id);
    } 
    
    @PostMapping("/save")
    @ResponseBody
    @OperateRecord(OperateName = "保存新闻",ModellName ="新闻管理")
    public Result<?> save(HttpServletRequest request,Camera camera) {
        try{ 
        	UserDO user = this.getUser(); 
        	if(camera.getId() != null){
        		Camera old = cameraService.getById(camera.getId());
        		old.setVideoImg(camera.getVideoImg())
        		    .setName(camera.getName())
        			.setGroupType(camera.getGroupType())
        			.setAppName(camera.getAppName())
        			.setFetchUrl(camera.getFetchUrl())
        			.setPushUrl(camera.getPushUrl())
        			.setSort(camera.getSort());
        		return cameraService.updateById(old) ? Result.ok():Result.fail();
        		
        	}else{
        	 	return cameraService.save(camera.setStatus(0).setCreateBy(user.getId()+"").setCreateTime(DateUtil.date().toString()))? Result.ok():Result.fail();
        	}
        }catch (Exception e){
            log.error(e.toString(),e);
            return Result.fail();
        } 
    }
    @GetMapping(value = "/show")
    public String show(String faceIds,Model model){  
    	model.addAttribute("varList",userFaceInfoService.findByFaceIds(Arrays.asList(StringUtils.split(faceIds,","))));
        return "face/show";
    }
    
    @GetMapping(value = "/showface") 
    public String showface(){  
    	return "face/showface";
    }
    
    @GetMapping(value = "/showfacedata")
    @ResponseBody
    public Result<?> showfacedata(String faceIds){  
    	List<UserFaceInfo> users = userFaceInfoService.findByFaceIds(Arrays.asList(StringUtils.split(faceIds,",")));
    	return Result.ok(users);
    }
}